package cn.yunhe.control;

import cn.yunhe.entity.Question;
import cn.yunhe.entity.Test;
import cn.yunhe.server.QuestionServer;
import cn.yunhe.server.ResultServer;
import cn.yunhe.server.TestServer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/InsertItemServlet")
public class InsertItemServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        QuestionServer questionServer = new QuestionServer();
        ResultServer resultServer =new ResultServer();
        TestServer testServer = new TestServer();
        PrintWriter out = response.getWriter();

        String tName = request.getParameter("tName"); //获取试题名称
        String allItem = request.getParameter("item"); //获取试题集合
        Test test = testServer.SelectTestId(tName); //获取试题对象
        int tId = test.gettId(); //获取试题编号

        String item = allItem.substring(1,allItem.length()-1); //去掉字符串两边中括号
        String[] Items = item.split(","); //拆分字符串
        int qId = 0; //定义一个试题编号
        for (int i=0;i<Items.length-1;i++){
            if (i == 0){
                String context = Items[i].substring(1,Items[i].length()-1); //获取试题名
                boolean flag = questionServer.InsertQuestion(context,tId); //插入试题
                if (flag){ //试题插入成功则查询试题编号
                    Question question = questionServer.AccureSelectQuestion(context); //查询试题对象
                    qId = question.getqId(); //将试题对象中的编号提取出来
                }
            }else {
                String answer = Items[Items.length-1].substring(1,Items[Items.length-1].length()-1);
                resultServer.InsertResult(Items[i].substring(1,Items[i].length()-1),qId,answer);
            }
        }
        out.print("提交成功!!");
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
